<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="5"
      :excludeValues="['startTime_begin', 'taskStartTime']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processInstanceId" label="流程实例ID">
          <FIInput v-model="state.query.processInstanceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="sequenceId" label="流程实例流水号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="activityDefKey" label="活动代码">
          <FIInput v-model="state.query.activityDefKey" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <!-- <FIFormItem name="taskStartTime" label="活动开始时间">
          <FIDatePicker v-model="state.query.taskStartTime" type="daterange" start-placeholder="" end-placeholder="" />
        </FIFormItem> -->
        <FIFormItem class="date-range-class" name="taskStartTime" label="活动开始时间">
          <FIDatePicker
            v-model="state.query.startTime_begin"
            value-format="YYYYMMDD"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(date, state.query.startTime_end)"
          />
          <FIDatePicker
            v-model="state.query.startTime_end"
            value-format="YYYYMMDD"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(state.query.startTime_begin, date)"
          />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="state" label="活动实例状态">
          <FISelect
            v-model="state.query.state"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'open', label: '正运行' },
              { value: 'completed', label: '已完成' },
              { value: 'closed', label: '关闭' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      height="300px"
      primaryKey="activityInstanceId"
      v-model:columns="columns"
      check-mode="radio"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      rowSelectable
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
    </FITable>
    <!-- 根据实例号查询对应任务列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}2`"
      :data="state.dataListTask"
      primaryKey="id"
      v-model:columns="taskColumns"
      check-mode="radio"
      :isLoading="isTableLoadingTask"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfigTask"
      :show-save-model="false"
      @table-refresh="searchFnTask"
      @selection-change="handleSelectionChangeTask"
      @size-change="handleSizeChangeTask"
      @current-page-change="handleCurrentChangeTask"
    >
      <template #headerBtn>
        <FIButton id="addTask" border @click="handleAdd">新增</FIButton>

        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要删除所数据吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="删除"
          :btn-binds="{ id: 'deleteTask', border: true }"
          :isVisible="!!checkedRowsTask.length"
          @confirm="deleteRow"
        />
      </template>
    </FITable>
    <addModel
      :id="state.taskId"
      :visible="showAddModel"
      :userArr="allStarterArr"
      @update:visible="(newValue) => (showAddModel = newValue)"
      @save-ok="handleSaveAddModelOk"
    />
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import addModel from './addModel.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import { apiQueryAllProcesses, apiQueryUser, apiQueryTask, apiQueryDept, apiQueryApp } from '@/api/modules/EWPT.js'
import { apiRequestPost, apiRequestPostFormData } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, checkDateDisabled } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
import FIButton from '@/components/FIButton.vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
const isTableLoadingTask = ref(false)
// 页面编码
const tableId = 'TaskMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)

const showAddModel = ref(false)
// 新增任务弹窗数据
const addModelData = ref(null)
const state = reactive({
  // 查询条件
  query: {
    processInstanceId: '', // 流程实例ID
    sequenceId: '', // 流程实例流水号
    activityDefKey: '', // 活动代码
    taskStartTime: '', // 流程开始时间
    startTime_begin: null, // 活动开始时间起点
    startTime_end: null, // 活动开始时间终点
    state: '', // 活动实例状态
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
  // 查询条件--任务
  queryTask: {
    activityInstanceId: '', // 流程实例ID
    current: 1,
    size: 10,
  },
  // 当前选中活动对应的第一条任务id
  taskId: '',
  // 表格数据--任务
  dataListTask: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 页面配置
const pageConfigTask: PageConfig = reactive({
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '实例号',
    prop: 'sequenceId',
    align: 'center',
    width: '120',
  },
  {
    label: '流程实例ID',
    prop: 'processInstanceId',
    align: 'center',
    width: '260',
  },
  {
    label: '活动实例ID',
    prop: 'activityInstanceId',
    align: 'center',
    width: '260',
  },
  {
    label: '流程定义编码',
    prop: 'processDefKey',
    align: 'center',
    width: '150',
  },
  {
    label: '流程定义名称',
    prop: 'processDefName',
    align: 'center',
    width: '150',
  },
  {
    label: '活动定义编码',
    prop: 'activityDefKey',
    align: 'center',
    width: '150',
  },
  {
    label: '活动定义名称',
    prop: 'activityName',
    align: 'center',
    width: '150',
  },
  {
    label: '活动状态',
    prop: 'state',
    align: 'center',
    width: '150',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'open', label: '正运行' },
        { value: 'completed', label: '结束' },
        { value: 'closed', label: '关闭' },
      ],
    },
  },
  {
    label: '活动开始时间',
    prop: 'startTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '活动结束时间',
    prop: 'endTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
])
const taskColumns: Column[] = reactive([
  {
    label: '任务ID',
    prop: 'id',
    align: 'center',
    width: '200',
  },
  {
    label: '任务名',
    prop: 'name',
    align: 'center',
    width: '200',
  },
  {
    label: '经办人ID',
    prop: 'assignee',
    align: 'center',
    width: '120',
  },
  {
    label: '经办人名称',
    prop: 'assigneeName',
    align: 'center',
    width: '120',
  },
  {
    label: '部门ID',
    prop: 'deptEname',
    align: 'center',
    width: '120',
  },
  {
    label: '部门名称',
    prop: 'deptCname',
    align: 'center',
    width: '150',
  },
  {
    label: '岗位ID',
    prop: 'roleEname',
    align: 'center',
    width: '120',
  },
  {
    label: '岗位名称',
    prop: 'roleCname',
    align: 'center',
    width: '130',
  },
  {
    label: '任务状态',
    prop: 'taskStatus',
    align: 'center',
    width: '100',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'open', label: '正运行' },
        { value: 'completed', label: '已完成' },
        { value: 'closed', label: '已关闭' },
      ],
    },
  },
  {
    label: '领取状态',
    prop: 'claimStatus',
    align: 'center',
    width: '100',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'false', label: '未领取' },
        { value: 'true', label: '已领取' },
        { value: 'claimed', label: '已被领取' },
      ],
    },
  },
  {
    label: '是否授权',
    prop: 'hasAuth',
    align: 'center',
    width: '120',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'false', label: '否' },
        { value: 'true', label: '是' },
      ],
    },
  },
  {
    label: '到达时间',
    prop: 'startTime',
    align: 'center',
    editType: 'date-picker',
    minWidth: '160',
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
  state.queryTask.activityInstanceId = checkedRows.value[0].activityInstanceId
  searchFnTask()
}
// 选中列表集合--task
const checkedRowsTask = ref([])
// 选中列表集合值改变回调函数--task
const handleSelectionChangeTask = (e) => {
  checkedRowsTask.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页大小改变回调函数--task
const handleSizeChangeTask = (e) => {
  pageConfigTask.pageSize = e
  pageConfigTask.currentPage = 1
  searchFnTask()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
// 分页页码改变回调函数--task
const handleCurrentChangeTask = (e) => {
  pageConfigTask.currentPage = e
  searchFnTask()
}
watch(
  () => state.query.taskStartTime,
  (newVal) => {
    if (!newVal) {
      state.query.startTime_begin = ''
      state.query.startTime_end = ''
    } else {
      if (newVal.length == 2) {
        state.query.startTime_begin = newVal[0]
        state.query.startTime_end = newVal[1]
      } else {
        state.query.startTime_begin = ''
        state.query.startTime_end = ''
      }
    }
  }
)
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
        state.dataListTask = []
        pageConfigTask.currentPage = 1
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// 搜索查询函数--task
const searchFnTask = (type?: string, columnsVal?: any) => {
  state.queryTask.current = pageConfigTask.currentPage
  isTableLoadingTask.value = true
  if (pageConfigTask.pageSize) state.queryTask.size = pageConfigTask.pageSize
  const apiUrl = proxy.$Button_api('queryTask', route.name)
  apiRequestPost(apiUrl, state.queryTask)
    .then((res) => {
      isTableLoadingTask.value = false
      if (res.data.success) {
        state.dataListTask = res.data.data.result
        pageConfigTask.pageSize = Number(res.data.data.size)
        pageConfigTask.total = Number(res.data.data.count)
        if (Array.isArray(state.dataListTask) && state.dataListTask.length > 0) {
          state.taskId = state.dataListTask[0].id
        } else {
          state.taskId = ''
        }
      }
    })
    .catch((error: any) => {
      isTableLoadingTask.value = false
      // 处理错误
    })
}
// 删除函数
const deleteRow = () => {
  if (!checkedRowsTask.value.length) {
    useMessage().warning('请至少选择一条数据！')
    return
  }
  if (state.dataListTask.length == 1) {
    useMessage().warning('只有一条任务不能删除')
    return
  }
  // let ids = []

  // Array.isArray(checkedRowsTask.value) &&
  // checkedRowsTask.value.forEach((item: any) => {
  //     if (item?.id) ids.push(item?.id)
  //   })
  let obj = { taskId: '' }
  if (Array.isArray(checkedRowsTask.value)) {
    obj.taskId = checkedRowsTask.value[0]?.id
  }
  isTableLoadingTask.value = true

  apiRequestPostFormData('/bpm-service/TaskMaint/deleteTask', obj)
    .then((res) => {
      isTableLoadingTask.value = false
      if (res.data.success) {
        useMessage().success('删除成功！')
        searchFnTask()
      }
    })
    .catch((error: any) => {
      isTableLoadingTask.value = false
    })
}
const handleAdd = () => {
  if (!state.queryTask.activityInstanceId || !state.taskId) {
    useMessage().warning('未选择活动节点或活动节点上无任务')
    return
  }
  showAddModel.value = true
}
// 新增任务成功回调
const handleSaveAddModelOk = () => {
  state.queryTask.current = 1
  state.dataListTask = []
  searchFnTask()
}

// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}
// const taskId = computed(() => {
//   if (Array.isArray(checkedRowsTask.value)) {
//     console.log('taskId---', checkedRowsTask.value[0]?.id)
//     return checkedRowsTask.value[0]?.id
//   }
//   return ''
// })
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
  getAllProcessesStarter()
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
